package web.weibo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import web.weibo.mapper.MapperUser;
import web.weibo.model.User;
import web.weibo.service.ServiceUser;
import web.weibo.service.ServiceWeibo;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

@Controller
public class ControllerUser {

    @Autowired
    private MapperUser mapperUser;
    @Autowired
    private ServiceUser serviceUser;
    @Autowired
    private ServiceWeibo serviceWeibo;

    public static void log(String format, Object... args) {
        System.out.println(String.format(format, args));
    }

    @GetMapping("/login/view")
    public ModelAndView loginView(HttpServletRequest request) {
        User user = ControllerHelper.currentUser(this.mapperUser, request);
        String note = user.note;
        String message = String.format("当前登录用户 %s", note);
        ModelAndView modelAndView = new ModelAndView("login");
        modelAndView.addObject("message", message);
        return modelAndView;
    }

    @PostMapping("/login")
    public ModelAndView login(String username, String password, HttpServletResponse response) {
        String sessionId = this.serviceUser.login(username, password);
        Cookie cookie;
        if (sessionId.length() > 0) {
            cookie = new Cookie("session_id", sessionId);
            response.addCookie(cookie);
            return new ModelAndView("redirect:/login/view");
        } else {
            ModelAndView modelAndView = new ModelAndView("login");
            modelAndView.addObject("message", "密码错误或您没有注册！");
            return modelAndView;
        }
    }

    @GetMapping("/register/view")
    public ModelAndView registerView() {
        ModelAndView modelAndView = new ModelAndView("register");
        modelAndView.addObject("message", "请注册");
        return modelAndView;
    }

    @PostMapping("/register")
    public ModelAndView register(String note, String username, String password) {
        String message;
        boolean validNote = ControllerHelper.formatNote(note);
        boolean validUsername = ControllerHelper.formatName(username);
        boolean validPassword = ControllerHelper.formatPass(password);
        boolean isUser = ControllerHelper.isUser(this.mapperUser, username);
        if (validNote) {
            if (validUsername) {
                if (isUser) {
                    if (validPassword) {
                        boolean success = this.serviceUser.register(note, username, password);
                        if (success) {
                            message = String.format("注册成功 %s", note);
                        } else {
                            message = "注册失败!";
                        }
                    } else {
                        message = "密码格式错误";
                    }
                } else {
                    message = "已有该账号，请登录";
                }
            } else {
                message = "账号格式错误";
            }
        } else {
            message = "用户名错误";
        }
        ModelAndView modelAndView = new ModelAndView("register");
        modelAndView.addObject("message", message);
        return modelAndView;
    }

    @GetMapping("/admin/users/view")
    public ModelAndView updatePasswordView() {
        ModelAndView modelAndView = new ModelAndView("updatePassword");
        modelAndView.addObject("message", "请修改密码!");
        return modelAndView;
    }

    @PostMapping("/admin/users/update")
    public ModelAndView updatePassword(String username, String oldPassword, String password) {
        String message = this.serviceUser.updatePassword(username, oldPassword, password);
        ModelAndView modelAndView = new ModelAndView("updatePassword");
        modelAndView.addObject("message", message);
        return modelAndView;
    }

    @GetMapping("/upload/view")
    public ModelAndView uploadView() {
        return new ModelAndView("upload");
    }

    @PostMapping("/upload")
    public ModelAndView upload(MultipartFile file) {
        log("filename %s size %s", file.getOriginalFilename(), file.getSize());
        Path path = Path.of("upload", file.getOriginalFilename());
        try {
            Files.write(path, file.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new ModelAndView("redirect:/upload/view");
    }

    @GetMapping("/uploaded")
    public void uploaded(HttpServletResponse response, String file) throws IOException {
        byte[] bytes = Files.readAllBytes(Path.of("upload", file));
        response.setContentType("image/jpeg");
        OutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        //关闭响应输出流
        out.close();
    }

    /**
     * 个人信息页面
     *
     * @param request
     * @return
     */
    @GetMapping("/profile")
    public ModelAndView profile(HttpServletRequest request) {
        User user = ControllerHelper.currentUser(this.mapperUser, request);
        int countWeibo = this.serviceWeibo.countWeibos(user.id);
        int comments = this.serviceWeibo.myAllComments(user.id);
        int countCares = this.serviceWeibo.countCares(user.id);
        int countBeCares = this.serviceWeibo.countBeCares(user.id);
        ModelAndView modelAndView = new ModelAndView("profile");
        modelAndView.addObject("user", user);
        modelAndView.addObject("countWeibo", countWeibo);
        modelAndView.addObject("comments", comments);
        modelAndView.addObject("countCares", countCares);
        modelAndView.addObject("countBeCares", countBeCares);
        return modelAndView;
    }

    @PostMapping("/avator/add")
    public ModelAndView avator(HttpServletRequest request, MultipartFile file) {
        log("filename %s size %s", file.getOriginalFilename(), file.getSize());
        String avatorName = file.getOriginalFilename();
        Path path = Path.of("avator", file.getOriginalFilename());
        try {
            Files.write(path, file.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ModelAndView modelAndView = new ModelAndView("profile");
        modelAndView.addObject("avatorName", avatorName);
        User user = ControllerHelper.currentUser(this.mapperUser, request);
        this.mapperUser.avator(avatorName, user.id);
        return new ModelAndView("redirect:/profile");
    }

    @GetMapping("/avator")
    public void avatorLoad(HttpServletResponse response, String file) throws IOException {
        byte[] bytes = Files.readAllBytes(Path.of("avator", file));
        response.setContentType("image/jpeg");
        try(OutputStream out = response.getOutputStream()) {
            out.write(bytes);
            out.flush();
        }
    }

    @GetMapping("/exit")
    public ModelAndView exit(HttpServletRequest request) {
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        this.serviceUser.exit(currentUser.username);
        ModelAndView modelAndView = new ModelAndView("login");
        modelAndView.addObject("message", "请重新登录！");
        return modelAndView;
    }
}
